package com.whisperly.echotalk.starryb.schemas;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.LocaleList;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.snackbar.Snackbar;
import com.whisperly.echotalk.account.FindPassword;
import com.whisperly.echotalk.bllmodel.UserWithChat;
import com.whisperly.echotalk.starryb.R;
import com.whisperly.echotalk.starryb.utils.AppsManager;
import com.whisperly.echotalk.starryb.utils.DatabaseHelper;
import com.whisperly.echotalk.starryb.utils.EmailUtil;
import com.whisperly.echotalk.starryb.utils.GlobalData;
import com.whisperly.echotalk.starryb.utils.MD5Utils;
import com.whisperly.echotalk.starryb.utils.Mutual;

import java.util.List;
import java.util.Locale;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;

public class Register extends AppCompatActivity {
    private EditText user_name, user_email, et_psw, et_cpsw, verification_code;
    private Button register, btnSendCode;
    private TextView login;
    private CheckBox checkbox_agree;
    private Toast currentToast;
    private CountDownTimer countDownTimer;
    private String userInputCode;
    private Toast current;
    private View loadingView;

    @Override
    protected void attachBaseContext(Context newBase) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newBase);
        String languageCode = prefs.getString("language", "en");
        super.attachBaseContext(updateResources(newBase, languageCode));
    }

    public Context updateResources(Context context, String languageCode) {
        Locale locale = new Locale(languageCode);
        Locale.setDefault(locale);

        Resources res = context.getResources();
        Configuration config = new Configuration(res.getConfiguration());
        config.setLocale(locale);
        LocaleList localeList = new LocaleList(locale);
        LocaleList.setDefault(localeList);
        config.setLocales(localeList);
        context = context.createConfigurationContext(config);
        return context;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        AppsManager.addActivity(this);

        user_name = findViewById(R.id.user_name);
        user_email = findViewById(R.id.user_email);
        et_psw = findViewById(R.id.et_psw);
        et_cpsw = findViewById(R.id.et_cpasw);
        register = findViewById(R.id.register);
        login = findViewById(R.id.login);
        btnSendCode = findViewById(R.id.btn_send_code);
        verification_code = findViewById(R.id.verification_code);
        checkbox_agree = findViewById(R.id.checkbox_agree);
        loadingView = getLayoutInflater().inflate(R.layout.layout_loading, null);

        TextView textView = findViewById(R.id.text_privacy);
        String fullText = getString(R.string.read_and_agree_to_the_terms_of_service);
        SpannableString spannableString = new SpannableString(fullText);

        btnSendCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = user_email.getText().toString().trim();
                if (isValidEmail(email)) {
                    startCountDown();
                    // 调用发送验证码的方法
                    EmailUtil.generateCode();
                    EmailUtil.sendEmail(email, v, Register.this);
                } else {
                    user_email.setError(getString(R.string.invalid_email_address));
                }

            }
        });


        setSpanWithClickAndColor(spannableString, "Blink Chat", () -> {

            openWebView("https://www.chen88.top", "Blink Chat");
        });
        setSpanWithClickAndColor(spannableString, getString(R.string.User_Agreement), () -> {

            openWebView("https://blinkchat-privacy.chen88.top/terms-condition.html", getString(R.string.User_Agreement));
        });
        setSpanWithClickAndColor(spannableString, getString(R.string.Privacy_Policy), () -> {

            openWebView("https://blinkchat-privacy.chen88.top", getString(R.string.Privacy_Policy));
        });

        textView.setMovementMethod(LinkMovementMethod.getInstance());
        textView.setText(spannableString);
        init();
    }

    private void startCountDown() {
        btnSendCode.setEnabled(false);
        countDownTimer = new CountDownTimer(60000, 1000) {
            public void onTick(long millisUntilFinished) {
                btnSendCode.setText(getString(R.string.resend_code_in, millisUntilFinished / 1000));
            }

            public void onFinish() {
                btnSendCode.setText(R.string.send_code);
                btnSendCode.setEnabled(true);
            }
        }.start();
    }

    private void setSpanWithClickAndColor(SpannableString spannableString, String textToHighlight, Runnable onClickAction) {
        int startIndex = spannableString.toString().indexOf(textToHighlight);
        int endIndex = startIndex + textToHighlight.length();
        if (startIndex == -1) return;


        spannableString.setSpan(new ForegroundColorSpan(Color.BLUE), startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);


        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                onClickAction.run();
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(false);
            }
        }, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    private void openWebView(String url, String title) {
        Intent intent = new Intent(this, Mutual.class);
        intent.putExtra("str1", url);
        intent.putExtra("str2", title);
        startActivity(intent);
    }


    private void init() {

        register.setOnClickListener(v -> {
            if (!checkbox_agree.isChecked()) {

                if (currentToast != null) {
                    currentToast.cancel();
                }
                currentToast = Toast.makeText(this, R.string.Please_read_and_agree_to_the_Privacy_Policy_first, Toast.LENGTH_SHORT);
                currentToast.show();
                return;
            }
            registerUser();
        });

        user_email.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                if (!isValidEmail(user_email.getText().toString())) {
                    user_email.setError(getString(R.string.invalid_email_address));
                }
            }
        });

        login.setOnClickListener(v -> {
            Intent intent = new Intent(this, Login.class);
            startActivity(intent);
//            overridePendingTransition(R.anim.slide_up, R.anim.slide_down);
            finish();
            Register.super.finish();
        });
    }

    private void registerUser() {
        showLoading();
        new Handler(Looper.getMainLooper()).postDelayed(()->{
            String name = user_name.getText().toString().trim();
            String email = user_email.getText().toString().trim();
            String psw = et_psw.getText().toString().trim();
            String cpsw = et_cpsw.getText().toString().trim();
            userInputCode = ((EditText) findViewById(R.id.verification_code)).getText().toString().trim();

            if (userInputCode.isEmpty()) {
                if (current != null) {
                    current.cancel();
                }
                current = Toast.makeText(this, R.string.Please_enter_the_verification_code, Toast.LENGTH_SHORT);
                current.show();
                verification_code.setError(getString(R.string.Please_enter_the_verification_code));
                hideLoading();
                return;

            }

            if (!EmailUtil.isCodeValid()) {
                if (current != null) {
                    current.cancel();
                }
                current = Toast.makeText(this, R.string.Verification_code_has_expired, Toast.LENGTH_SHORT);
                current.show();
                verification_code.setError(getString(R.string.Verification_code_has_expired));
                showLoading();
                return;
            }

            if (!userInputCode.equals(EmailUtil.getVerificationCode())) {
                if (current != null) {
                    current.cancel();
                }
                current = Toast.makeText(this, R.string.Verification_code_is_incorrect, Toast.LENGTH_SHORT);
                current.show();
                verification_code.setError(getString(R.string.Verification_code_is_incorrect));
                showLoading();
                return;
            }

            if (name.length() == 0 || email.length() == 0 || psw.length() == 0 || cpsw.length() == 0) {
                showRegisterDialog(getString(R.string.Please_d_leave_it_blank), false);
                showLoading();
                return;
            }
            if (!isValidEmail(email)) {
                showRegisterDialog(getString(R.string.invalid_email_address), false);
                user_email.setError(getString(R.string.invalid_email_address));
                showLoading();
                return;
            }
            if (!psw.equals(cpsw)) {
                showRegisterDialog(getString(R.string.The_password_is_inconsistent_twice), false);
                et_cpsw.setError(getString(R.string.The_password_is_inconsistent_twice));
                showLoading();
                return;
            }

            BmobQuery<UserWithChat> bmobQuery = new BmobQuery<>();
            bmobQuery.findObjects(new FindListener<UserWithChat>() {
                @Override
                public void done(List<UserWithChat> list, BmobException e) {
                    if (list != null) {
                        for (UserWithChat u : list) {
                            if (u.getName().contentEquals(name)) {
                                showRegisterDialog(getString(R.string.The_account_already_exists_Please_register_again), false);
                                user_name.setError(getString(R.string.The_account_already_exists_Please_register_again));
                                return;
                            }
                            if (u.getEmail().contentEquals(email)) {
                                showRegisterDialog(getString(R.string.The_email_address_alread_exists), false);
                                user_email.setError(getString(R.string.The_email_address_alread_exists));
                                return;
                            }
                        }
                    }
                    String finalPsw = MD5Utils.stringMD5(psw);
                    UserWithChat user = new UserWithChat(name, finalPsw, 2, email);
                    user.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            if (e == null) {
                                Log.e("loginId",s);
                                Log.e("loginId",user.getObjectId());
                                Log.e("user",user.toString());
                                showRegisterDialog(getString(R.string.Registration_Successful), true);
                            } else {
                                Log.e("loginId",e.toString());
                                showRegisterDialog(getString(R.string.Registration_failed_Please_try_again_later), false);
                            }
                        }
                    });
                }
            });
            hideLoading();
        },1000);
    }

    private void showRegisterDialog(String message, boolean flag) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("PROMPT");
        builder.setMessage(message);
        builder.setPositiveButton("OK", (dialog, which) -> {
            if (flag) {
                Intent intent = new Intent(this, Login.class);
                startActivity(intent);
//                overridePendingTransition(R.anim.slide_out_left, R.anim.slide_in_right);
                dialog.dismiss();
                finish();
                super.finish();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.setCancelable(false);
        dialog.show();
    }

    private void showLoading() {
        if (loadingView.getParent() == null) {
            ((ViewGroup) findViewById(android.R.id.content)).addView(loadingView);
            Log.d("LoginActivity", "Loading view added");
        }
    }

    private void hideLoading() {
        ((ViewGroup) findViewById(android.R.id.content)).removeView(loadingView);
    }

    private boolean isValidEmail(String email) {
        return Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
}
